package com.ruoyi.web.sso.common.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PasswordUtil {
    private static MessageDigest digest = null;
    public static String encryptPassword(String loginName, String password, String salt)
    {
        return encode(loginName + password + salt);
    }

    /**
     * 对字符串进行MD5加密
     * @param data
     * @return
     */
    public static String encode(String data) {
        if (digest == null)
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException nsae) {
                nsae.printStackTrace();
            }
        digest.update(data.getBytes());
        return encodeHex(digest.digest());
    }

    private static String encodeHex(byte bytes[]) {
        StringBuffer buf = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            if ((bytes[i] & 0xff) < 16)
                buf.append("0");
            buf.append(Long.toString(bytes[i] & 0xff, 16));
        }
        return buf.toString().toUpperCase();
    }

    public static void main(String[] args) {
        System.out.println(createOrderNo());
    }

    /*** 创建6随机 */
    public static String createOrderNo() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = format.format(new Date());
        String code = time.substring(10, 14) + (int) (10 + Math.random() * (99 - 10 + 1));
        return code;
    }

    /**
     * Java 等效实现前端 md5 函数
     *
     * @param input  要加密的字符串
     * @param key    HMAC 密钥（可选）
     * @param raw    是否返回原始字节数组（true）或十六进制字符串（false）
     * @return 加密后的结果（字节数组或十六进制字符串）
     */
    public static Object md5(String input, String key, boolean raw) {
        if (input == null || input.isEmpty()) {
            return raw ? new byte[0] : "0";
        }

        try {
            if (key == null || key.isEmpty()) {
                // 普通 MD5
                MessageDigest digest = MessageDigest.getInstance("MD5");
                byte[] hash = digest.digest(input.getBytes("UTF-8"));
                return raw ? hash : toHex(hash);
            } else {
                // HMAC-MD5
                Mac mac = Mac.getInstance("HmacMD5");
                SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacMD5");
                mac.init(secretKey);
                byte[] hash = mac.doFinal(input.getBytes("UTF-8"));
                return raw ? hash : toHex(hash);
            }
        } catch (Exception e) {
            throw new RuntimeException("MD5 计算失败", e);
        }
    }

    /**
     * 将字节数组转换为十六进制字符串
     */
    private static String toHex(byte[] bytes) {
        StringBuilder hex = new StringBuilder();
        for (byte b : bytes) {
            String hexString = Integer.toHexString(0xff & b);
            if (hexString.length() == 1) {
                hexString = "0" + hexString;
            }
            hex.append(hexString);
        }
        return hex.toString();
    }


}
